<script setup lang="ts">
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/css";
import GoodsSelect from "~/components/GoodsSelect.vue";
import AudioItem from "~/components/AudioItem.vue";
import ImageItem from "~/components/ImageItem.vue";
import { getBuyerDetailById } from "~/api/goods";
// 注释掉不需要的API导入
// import { commentPage, recommendGoods } from "~/api/goods";
// import { addBuyerConcern } from "~/api/user";
import { followShop, cancelFollowShop } from "~/api/user";
import { useSocketStore } from "~/store/useSocket";
import { onMounted, ref, computed, watch } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { Check } from '@element-plus/icons-vue';
import { useUserStore } from "~/store/useUser";
import { actionAuthGuard } from "~/utils/authGuard";
import defoultImg from "~/assets/app-mj.png";
import followIcon from "~/assets/follow-icon.png";
import followIconActive from "~/assets/follow-icon-active.png";
import { getCreditLevel, getNumUnit, getScore } from "~/utils/func";
import { useImageCache } from "~/composables/useImageCache";
import { nextTick } from "vue";
import type {
  BuyerGoodsDetailVo,
  GoodsResourceVo,
  GoodsSkuVo,
  Response as GoodsDetailResponse
} from "~/types/goods";


// 只在客户端加载 ldrs
if (process.client) {
  const { tailChase } = await import('ldrs')
  tailChase.register()
}

useSeoMeta({
  title: "商品详情 - 技能猴子",
  ogTitle: "商品详情 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

const router = useRouter();
const socketStore = useSocketStore();
const route = useRoute();
const userStore = useUserStore();
const { getCoverImage, imageUrlCache } = useImageCache();
const goodsId = computed(() => {
  const id = route.query.id;
  console.log('路由参数ID:', id);
  console.log('完整路由信息:', route);
  return id;
});

// 获取商品详情
const details = ref<any>({});
// 店铺关注状态
const isFollowingShop = ref(false);
// 获取默认显示的商品详情图文内容
const defaultContent = computed(() => {
  if (!details.value.introduce) return [];
  const introduce = details.value.introduce.introduce;
  return introduce.split(",");
});

// 处理资源数据
const audioResources = computed((): GoodsResourceVo[] => {
  return details.value.audioResources || [];
});

const videoResources = computed((): GoodsResourceVo[] => {
  const videos = details.value.videoResources || [];
  console.log('videoResources:', videos);
  return videos;
});

const documentResources = computed((): GoodsResourceVo[] => {
  const documents = details.value.documentResources || [];
  console.log('documentResources:', documents);
  console.log('documentResources structure:', documents.map(doc => ({
    id: doc.id,
    title: doc.title,
    fileSize: doc.fileSize,
    url: doc.url,
    mainPic: doc.mainPic
  })));
  return documents;
});

const imageResources = computed((): GoodsResourceVo[] => {
  const images = details.value.imageResources || [];
  console.log('imageResources:', images);
  return images;
});

// 添加activeTab状态控制资源标签页切换
const activeTab = ref<string>('details');

// 处理轮播图显示的computed属性，确保图片缓存更新后能正确显示
const displayCoverPic = computed(() => {
  if (!details.value.baseInfo?.coverPic) return [];
  
  const processedImages = details.value.baseInfo.coverPic.map(item => {
    if (!item) return '';
    
    // 如果已经是完整URL，直接返回
    if (item.includes('http')) {
      return item.split(',')[0];
    }
    
    // 如果是本地资源路径，直接返回
    if (item.startsWith('~/') || item.startsWith('@/')) {
      return item;
    }
    
    // 从缓存中获取真实URL
    const cachedUrl = imageUrlCache.value?.[item];
    if (cachedUrl) {
      return cachedUrl;
    }
    
    // 如果缓存中没有，返回OSS ID（会触发异步加载）
    return item;
  }).filter(item => item);
  
  // 触发图片异步加载
  details.value.baseInfo.coverPic.forEach(item => {
    if (item && !item.includes('http') && !item.startsWith('~/') && !imageUrlCache.value?.[item]) {
      getCoverImage(item); // 这会触发异步加载
    }
  });
  
  return processedImages;
});
const getDetails = async (id: string | number): Promise<void> => {
  try {
    console.log('开始请求商品详情，ID:', id);
    const data = await getBuyerDetailById({
      id,
    });
    if (data && data.data) {
      // 适配新的数据格式
      if (data.data.baseInfo) {
        // 旧数据格式，保持原有处理逻辑
        details.value = data.data;

        // 设置审核状态，确保购买按钮能够显示
        if (!details.value.baseInfo.auditStatus) {
          details.value.baseInfo.auditStatus = true;
        }

        // 确保 startServiceTimes 被正确传递
        if (details.value.baseInfo.startServiceTimes === undefined && data.data.startServiceTimes !== undefined) {
          details.value.baseInfo.startServiceTimes = data.data.startServiceTimes;
        }

        // 如果有goodsResources数据，使用goodsResources作为轮播图数据源
        if (data.data.goodsResources && Array.isArray(data.data.goodsResources)) {
          console.log('旧数据格式，发现goodsResources数据:', data.data.goodsResources);
          details.value.baseInfo.coverPic = data.data.goodsResources.map(item => item.mainPic?.trim()).filter(item => item);
          console.log('旧数据格式，使用goodsResources处理后的轮播图数据:', details.value.baseInfo.coverPic);
        } else {
          console.log('旧数据格式，未找到goodsResources数据，使用原有coverPic数据:', details.value.baseInfo.coverPic);
        }

        // 检查轮播图数据类型和内容
        if (details.value.baseInfo.coverPic) {
          console.log('轮播图数据类型:', typeof details.value.baseInfo.coverPic);
          if (Array.isArray(details.value.baseInfo.coverPic)) {
            console.log('轮播图数组长度:', details.value.baseInfo.coverPic.length);
            console.log('轮播图数组内容:', JSON.stringify(details.value.baseInfo.coverPic));
          }
        }
      } else if (data.data.id) {
        // 新数据格式，转换为旧格式结构
        // 处理轮播图数据：coverPic、coverVideo、mainPic
        const slideshowImages = [];

        // 使用getCoverImage处理所有图片
        // 添加封面图
        if (data.data.coverPic) {
          slideshowImages.push(getCoverImage(data.data.coverPic));
        }

        // 添加视频封面
        if (data.data.coverVideo) {
          slideshowImages.push(getCoverImage(data.data.coverVideo));
        }

        // 添加商品资源中的主图
        if (data.data.goodsResources && Array.isArray(data.data.goodsResources)) {
          data.data.goodsResources.forEach(item => {
            if (item.mainPic) {
              slideshowImages.push(getCoverImage(item.mainPic.trim()));
            }
          });
        }

        // 如果没有图片，添加默认图片
        if (slideshowImages.length === 0) {
          slideshowImages.push(defoultImg);
        }

        details.value = {
          baseInfo: {
            id: data.data.id,
            goodsName: data.data.goodsName,
            goodsTypeName: data.data.typeName,
            shopAvatar: data.data.shopAvatar, // 店铺Logo（OSS ID）
            coverPic: slideshowImages.filter(item => item), // 过滤掉空值
            sysUserId: data.data.shopId,
            nickName: data.data.shopName || '未知用户',
            profile: data.data.shopProfile,
            score: data.data.score,
            commentCount: data.data.orderCount || 0,
            creditLevel: data.data.creditLevel,
            creditScore: data.data.creditScore,
            saleCount: data.data.saleCount,
            deliveryRate: data.data.deliveryRate,
            replyRate: data.data.replyRate,
            uimKey: data.data.shopId,
            isBond: data.data.isBond,
            bondAmount: data.data.bondAmount,
            auditStatus: true,  // 设置审核状态，确保购买按钮能够显示
            startServiceTimes: data.data.startServiceTimes ?? 0, // 开启服务时间
            isFollowed: data.data.isFollowed ?? false // 是否关注店铺
          },
          introduce: {
            introduce: data.data.introduce || ''
          },
          labelList: (data.data.labels || '').split(',').map(label => ({ label }))
        };

        // 设置关注状态
        isFollowingShop.value = data.data.isFollowed ?? false;

        // 处理商品规格数据
        if (data.data.goodsSpecifications && data.data.goodsSpecifications.length > 0) {
          // 标准版 - 优先根据skuType识别，如果没有skuType=1的，则使用isDefault=1的
          const standardSpec = data.data.goodsSpecifications.find(spec => spec.skuType === 1) ||
            data.data.goodsSpecifications.find(spec => spec.isDefault === 1);
          if (standardSpec) {
            details.value.standard = {
              id: standardSpec.id,
              goodsAmount: standardSpec.goodsAmount,
              deliverDays: standardSpec.deliverDays,
              introduce: standardSpec.skuName,
              inCart: !!standardSpec.inCart,
              detailsServer: standardSpec.features?.map(feature => ({
                content: typeof feature === 'object' ? feature.content : feature
              })) || []
            };
          }

          // 体验版 - 根据skuType=2识别
          const trialSpec = data.data.goodsSpecifications.find(spec => spec.skuType === 2);
          if (trialSpec) {
            details.value.experience = {
              id: trialSpec.id,
              goodsAmount: trialSpec.goodsAmount,
              deliverDays: trialSpec.deliverDays,
              introduce: trialSpec.skuName,
              inCart: !!trialSpec.inCart,
              detailsServer: trialSpec.features?.map(feature => ({
                content: typeof feature === 'object' ? feature.content : feature
              })) || []
            };
          }

          console.log('处理SKU数据:', {
            totalSpecs: data.data.goodsSpecifications.length,
            standardSpec: standardSpec ? { id: standardSpec.id, skuType: standardSpec.skuType, isDefault: standardSpec.isDefault } : null,
            trialSpec: trialSpec ? { id: trialSpec.id, skuType: trialSpec.skuType, isDefault: trialSpec.isDefault } : null
          });
        }

        // 处理资源数据
        details.value.audioResources = data.data.audioResources || [];
        details.value.videoResources = data.data.videoResources || [];
        details.value.imageResources = data.data.imageResources || [];
        details.value.documentResources = data.data.documentResources || [];
        
        console.log('资源数据加载完成:');
        console.log('audioResources:', data.data.audioResources);
        console.log('videoResources:', data.data.videoResources);
        console.log('imageResources:', data.data.imageResources);
        console.log('documentResources:', data.data.documentResources);

        // 处理轮播图数据
        console.log('新数据格式，goodsResources数据:', data.data.goodsResources);
        if (data.data.goodsResources && Array.isArray(data.data.goodsResources)) {
          console.log('轮播图数据来源: goodsResources, 数组长度:', data.data.goodsResources.length);
          console.log('处理后的轮播图数据:', details.value.baseInfo.coverPic);
        }

        console.log('新数据格式，处理后的轮播图数据:', details.value.baseInfo.coverPic);
        // 检查轮播图数据类型和内容
        if (details.value.baseInfo.coverPic) {
          console.log('轮播图数据类型:', typeof details.value.baseInfo.coverPic);
          if (Array.isArray(details.value.baseInfo.coverPic)) {
            console.log('轮播图数组长度:', details.value.baseInfo.coverPic.length);
            console.log('轮播图数组内容:', JSON.stringify(details.value.baseInfo.coverPic));
          }
        }
      }
      console.log('设置商品详情数据成功');

      // 设置标题
      if (details.value.baseInfo && details.value.baseInfo.goodsName) {
        setTitle(details.value.baseInfo.goodsName);
        console.log('设置标题成功:', details.value.baseInfo.goodsName);
      }

      // 检查店铺关注状态 - 现在直接从接口数据获取，不需要额外调用
      // if (details.value.baseInfo && details.value.baseInfo.sysUserId) {
      //   checkShopFollowStatus(details.value.baseInfo.sysUserId);
      // }
    } else {
      console.error('商品详情数据格式不正确:', data);
    }

    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
  } catch (e) {
    console.error('获取商品详情失败', e);
    ElMessage.error('获取商品详情失败，请稍后重试');
  }
};

// 店铺关注/取消关注
const handleShopFollow = async () => {
  // 检查登录状态
  if (!actionAuthGuard({ requireAuth: true, message: '请先登录后再关注店铺' })) {
    return;
  }

  try {
    if (!details.value.baseInfo || !details.value.baseInfo.sysUserId) {
      ElMessage.error('店铺信息不完整，无法执行关注操作');
      return;
    }

    const shopId = details.value.baseInfo.sysUserId;

    if (isFollowingShop.value) {
      // 取消关注
      const response = await cancelFollowShop({ shopId });
      if (response && response.code === 200) {
        isFollowingShop.value = false;
        // 更新详情数据中的关注状态
        if (details.value.baseInfo) {
          details.value.baseInfo.isFollowed = false;
        }
        ElMessage.success('已取消关注');
      } else {
        ElMessage.error(response?.msg || '取消关注失败');
      }
    } else {
      // 关注店铺
      const response = await followShop({ shopId });
      if (response && response.code === 200) {
        isFollowingShop.value = true;
        // 更新详情数据中的关注状态
        if (details.value.baseInfo) {
          details.value.baseInfo.isFollowed = true;
        }
        ElMessage.success('关注成功');
      } else {
        ElMessage.error(response?.msg || '关注失败');
      }
    }
  } catch (error) {
    console.error('店铺关注操作失败', error);
    ElMessage.error('操作失败，请稍后重试');
  }
};

// 复制分享链接
const copyShareLink = () => {
  const shareUrl = `${window.location.origin}/details?id=${goodsId.value}`;
  const textarea = document.createElement('textarea');
  textarea.value = shareUrl;
  textarea.style.position = 'fixed';  // 防止页面滚动
  document.body.appendChild(textarea);
  textarea.select();

  try {
    const successful = document.execCommand('copy');
    if (!successful) {
      ElMessage.error('复制失败');
    }
    ElMessage.success({
      message: '复制成功',
      duration: 1000,
      icon: Check,
      plain: true
    });
  } catch (err) {
    ElMessage.error('复制失败');
  }
  document.body.removeChild(textarea);
};

// 检查店铺关注状态
const checkShopFollowStatus = async (shopId) => {
  try {
    // 现在直接从商品详情接口的 isFollowed 字段获取关注状态
    // 不需要额外的API调用
    console.log('检查店铺关注状态，店铺ID:', shopId, '关注状态:', isFollowingShop.value);
  } catch (error) {
    console.error('检查店铺关注状态失败', error);
  }
};

// 获取商品id
const isClient = ref(false);
onMounted(() => {
  // 标记为客户端
  isClient.value = true;

  console.log('onMounted 触发');
  console.log('当前路由:', window.location.href);
  console.log('route.fullPath:', route.fullPath);
  console.log('route.path:', route.path);
  console.log('route.query:', route.query);

  // 获取商品id
  // 在监听 goodsId 的 watch 中处理首次与后续请求，这里不再触发
});

watch(goodsId, (newVal) => {
  console.log('商品ID变化:', newVal);
  if (newVal) {
    getDetails(newVal);
    // 滚动到顶部
    // window.scrollTo({
    //   top: 0,
    //   behavior: "auto",
    // });
  }
}, { immediate: true }); // 添加immediate:true，确保组件创建时立即执行一次

const mySwiperRef = ref(null);
const afterInit = (e) => {
  mySwiperRef.value = e;
};
const tapPrev = () => {
  if (mySwiperRef.value) {
    mySwiperRef.value.slidePrev(); // 直接访问 swiper 实例并调用方法
  }
};
const tapNext = () => {
  if (mySwiperRef.value) {
    mySwiperRef.value.slideNext();
  }
};
// 获取评论
// const commentParams = ref({
//   pageNum: 1,
//   pageSize: 10,
// });
// const commentList = ref([]);
// const totalCount = ref(0);
// const goodCount = ref(0);
// const neutralCount = ref(0);
// const negativeCount = ref(0);
// const commentType = ref(null);
// const setCommentType = (type) => {
//   commentType.value = type;
//   getCommentPage();
// };
// const getCommentPage = async () => {
//   try {
//     if (commentParams.value.pageNum === 1) {
//       commentList.value = [];
//     }

//     // 确保必要的参数存在
//     if (!goodsId.value || !details.value.baseInfo) {
//       console.log('获取评论所需参数不完整');
//       return;
//     }

//     commentParams.value.goodsId = goodsId.value;
//     commentParams.value.saleUserId = details.value.baseInfo.sysUserId;
//     if (commentType.value) {
//       commentParams.value.type = commentType.value;
//     } else {
//       delete commentParams.value.type;
//     }

//     const data = await commentPage(commentParams.value);
//     if (data && data.data) {
//       commentList.value = data.data.commentList || [];
//       if (!totalCount.value) totalCount.value = Number(data.data.totalCount || 0);
//       if (!goodCount.value) goodCount.value = Number(data.data.goodCount || 0);
//       neutralCount.value = data.data.neutralCount || 0;
//       negativeCount.value = data.data.negativeCount || 0;
//     }
//   } catch (e) {
//     console.log('获取评论失败', e);
//     // 请求失败不影响页面其他功能
//   }
// };
// 关注
// const follow = async () => {
//   try {
//     // 确保必要的参数存在
//     if (!details.value.baseInfo || !details.value.baseInfo.sysUserId) {
//       console.log('关注操作所需参数不完整');
//       return;
//     }

//     const add = await addBuyerConcern({
//       goodsUserId: details.value.baseInfo.sysUserId,
//     });

//     // 切换关注状态
//     if (details.value.baseInfo.isConcern) {
//       details.value.baseInfo.isConcern = false;
//     } else {
//       details.value.baseInfo.isConcern = true;
//     }
//   } catch (e) {
//     console.log('关注操作失败', e);
//     // 请求失败不影响页面其他功能
//     ElMessage.error('关注操作失败，请稍后重试');
//   }
// };
// 为你推荐
// const recommendList = ref([]);
// const getRecommendList = async () => {
//   try {
//     // 确保必要的参数存在
//     if (!details.value.baseInfo || !details.value.baseInfo.id) {
//       console.log('获取推荐商品所需参数不完整');
//       return;
//     }

//     const data = await recommendGoods({
//       goodsId: details.value.baseInfo.id,
//       pageNum: 1,
//       pageSize: 8,
//     });

//     if (data && data.data && data.data.rows) {
//       recommendList.value = data.data.rows;
//     }
//   } catch (e) {
//     console.log('获取推荐商品失败', e);
//     // 请求失败不影响页面其他功能
//   }
// };

// 在线状态
const isOnline = computed(() => {
  return details.value.baseInfo?.onlineStatus === 1;
});
// 设置标题
const setTitle = (title) => {
  useHead({
    title: `${title} - 技能猴子`,
    ogTitle: `${title} - 技能猴子`,
    description: `${title} - 技能猴子`,
    ogDescription: `${title} - 技能猴子`,
  });
};
const enterUserHome = () => {
  const uid = details.value?.baseInfo?.sysUserId;
  if (!uid) {
    ElMessage.error('店铺信息不完整');
    return;
  }
  if (!userStore.isLogin) {
    ElMessage.warning('请先登录');
    router.push({ path: '/login', query: { redirect: `/userHomePage?uid=${uid}` } });
    return;
  }
  router.push({ path: '/userHomePage', query: { uid } });
};
// 刷新
const toDetails = (dataItem) => {
  console.log(dataItem);
  router.push({
    path: "/details",
    query: {
      id: dataItem.id,
    },
  });
};
// 头像：优先使用店铺 Logo 的 OSS ID（shopAvatar），否则回退到 profile，再到默认图
const profile = computed(() => {
  const avatarOssId = details.value?.baseInfo?.shopAvatar;
  if (avatarOssId) {
    return getCoverImage(avatarOssId);
  }
  if (details.value.baseInfo && details.value.baseInfo.profile) {
    return details.value.baseInfo.profile;
  }
  return defoultImg;
});
</script>

<template>
  <div class="details">
    <BaseHeaderMenuWhite bg-color="white" />
    <div class="content" v-if="details && details.baseInfo">
      <div class="info">
        <div class="info-left">
          <div class="swiper-box">
            <swiper :loop="true" :slides-per-view="1" :space-between="200" @afterInit="afterInit">
              <template v-if="displayCoverPic && displayCoverPic.length > 0">
                <swiper-slide v-for="(item, index) of displayCoverPic" :key="index">
                  <img v-if="item && (item.toLowerCase().indexOf('png') !== -1)" class="swiper-img" :src="item"
                    alt="" />
                  <img v-else-if="item && (item.toLowerCase().indexOf('jpg') !== -1)" class="swiper-img" :src="item"
                    alt="" />
                  <img v-else-if="item && (item.toLowerCase().indexOf('jpeg') !== -1)" class="swiper-img" :src="item"
                    alt="" />
                  <img v-else-if="item && (item.toLowerCase().indexOf('gif') !== -1)" class="swiper-img" :src="item"
                    alt="" />
                  <img v-else-if="item && (item.toLowerCase().indexOf('webp') !== -1)" class="swiper-img" :src="item"
                    alt="" />
                  <img v-else-if="item && (item.toLowerCase().indexOf('bmp') !== -1)" class="swiper-img" :src="item"
                    alt="" />
                  <video v-else-if="item && (item.toLowerCase().indexOf('mp4') !== -1)" controls class="swiper-img"
                    :src="item" alt="">
                    <!-- 自定义一个播放暂停按钮 -->
                  </video>
                  <img v-else class="swiper-img" :src="item || defoultImg" alt="" />
                </swiper-slide>
              </template>
              <template v-else>
                <swiper-slide>
                  <img class="swiper-img" :src="defoultImg" alt="" />
                </swiper-slide>
              </template>
            </swiper>
            <!-- 自定义的左箭头 -->
            <div class="prev" @click="tapPrev">
              <img src="~/assets/more-left.png" alt="" />
            </div>
            <!-- 自定义的右箭头 -->
            <div class="next" @click="tapNext">
              <img src="~/assets/more-right.png" alt="" />
            </div>
          </div>
          <!--					-->
          <div class="goods-name-container">
            <p class="goods-name">{{ details.baseInfo.goodsName }}</p>
            <div class="copy-button" @click="copyShareLink" title="复制分享链接">
              <img src="~/assets/check-more-icon-2.png" alt="复制" />
              <span>复制链接</span>
            </div>
          </div>
          <div class="goods-cate">
            <span class="class">所属品类：{{ details.baseInfo.goodsTypeName }}</span>
            <span v-for="item of details.labelList">{{ item.label }}</span>
          </div>
          <div class="about-info">
            <p class="title">
              <span>关于卖家</span>
              <a href="#" @click.prevent="enterUserHome">进入主页 <img
                  src="~/assets/check-more-icon-2.png" alt="" /></a>
            </p>
            <div class="user-main-info">
              <img class="head" :src="profile" alt="" />
              <div class="name-info">
                <div class="name-line">
                  <span class="name">{{ details.baseInfo.nickName }}</span>
                  <!-- 店铺关注功能 -->
                  <div class="follow" @click="handleShopFollow"
                    style="cursor: pointer; display: flex; align-items: center;">
                    <img :src="isFollowingShop ? followIconActive : followIcon" alt="" />
                    <span class="x-status" :class="{ followed: isFollowingShop }">{{ isFollowingShop ? '已关注' : '关注'
                      }}</span>
                  </div>
                </div>
                <p class="bzj" v-if="details.baseInfo.isBond">
                  <img src="~/assets/bzj-icon.png" alt="" />
                  <span>已缴纳保证金：{{ details.baseInfo.bondAmount }}元</span>
                </p>
              </div>
              <div class="x-leve">
                <p class="x-title">信用等级</p>
                <p class="x-status">
                  {{ getCreditLevel(details.baseInfo.creditLevel) }}
                </p>
                <p class="status-num">分值{{ details.baseInfo.creditScore }}</p>
              </div>
              <span class="line"></span>
              <div class="x-leve">
                <p class="x-title">总销量</p>
                <p class="x-status">
                  {{ getNumUnit(details.baseInfo.saleCount) }}
                </p>
                <p class="status-num">准时交付率 {{ details.baseInfo.deliveryRate || 0 }}%</p>
              </div>
            </div>
          </div>
        </div>
        <div class="info-right">
          <div class="user-info">
            <div class="head">
              <img :src="profile" alt="" />
              <span :class="isOnline ? 'online' : 'offline'"></span>
            </div>
            <div class="info-data">
              <div class="name-line">
                <span class="name">{{ details.baseInfo.nickName }}</span>
                <!-- 店铺关注功能 -->
                <span class="follow" @click="handleShopFollow"><img
                    :src="isFollowingShop ? followIconActive : followIcon" alt="" /><span
                    :class="{ followed: isFollowingShop }">{{ isFollowingShop ? '已关注' : '关注' }}</span></span>
              </div>
              <div class="user-data">
                <div class="online">
                  <span :class="['status', isOnline ? 'online' : 'offline']">{{ isOnline ? '在线' : '离线' }}</span>
                  <span v-if="details.baseInfo.replyRate"> · 3分钟内回复率 {{ details.baseInfo.replyRate || 0 }}%</span>
                </div>
                <img class="star" src="~/assets/mack-icon.png" alt="" />
                <span class="star-num">{{ details.baseInfo.score }}</span>
                <span class="star-len">({{ getNumUnit(details.baseInfo.commentCount) }})</span>
              </div>
            </div>
          </div>
          <GoodsSelect :details="details" />
        </div>
      </div>
      <!--	服务介绍	-->
      <div class="service-details">
        <div class="service-tab">
          <span :class="{ active: activeTab === 'details' }" @click="activeTab = 'details'">服务详情</span>
          <span :class="{ active: activeTab === 'audio' }" @click="activeTab = 'audio'"
            v-if="audioResources.length > 0">音频</span>
          <span :class="{ active: activeTab === 'video' }" @click="activeTab = 'video'">视频</span>
          <span :class="{ active: activeTab === 'image' }" @click="activeTab = 'image'" 
            v-if="imageResources.length > 0">图片</span>
          <span :class="{ active: activeTab === 'document' }" @click="activeTab = 'document'">文档</span>
        </div>
      </div>
      <div class="service-content">
        <!-- 服务详情 -->
        <div class="service-1" v-if="activeTab === 'details'">
          <img v-for="item of defaultContent" :key="item" :src="item" alt="" />
          <div class="introduce" v-if="details.introduce && details.introduce.introduce">
            <div v-html="details.introduce.introduce"></div>
          </div>
        </div>

        <!-- 音频资源 -->
        <div class="service-2" v-if="activeTab === 'audio'">
          <div v-for="item in audioResources" :key="item.id" class="resource-item">
            <AudioItem 
              :title="item.title" 
              :ossid="item.id" 
              :original-name="item.originalName || item.title" 
            />
          </div>
          <div class="empty-box" v-if="audioResources.length === 0">
            <el-empty description="暂无音频资源" />
          </div>
        </div>

        <!-- 视频资源 -->
        <div class="service-2" v-if="activeTab === 'video'">
          <div v-for="item in videoResources" :key="item.id" class="resource-item">
            <VideoItem 
              :title="item.title" 
              :ossid="item.id" 
              :original-name="item.originalName || item.title" 
              :main-pic="item.mainPic"
            />
          </div>
          <div class="empty-box" v-if="videoResources.length === 0">
            <el-empty description="暂无视频资源" />
          </div>
        </div>

        <!-- 图片资源 -->
        <div class="service-3" v-if="activeTab === 'image'">
          <div v-for="item in imageResources" :key="item.id" class="resource-item">
            <ImageItem 
              :title="item.title" 
              :ossid="item.id" 
              :original-name="item.originalName || item.title" 
            />
          </div>
          <div class="empty-box" v-if="imageResources.length === 0">
            <el-empty description="暂无图片资源" />
          </div>
        </div>

        <!-- 文档资源 -->
        <div class="service-4" v-if="activeTab === 'document'">
          <div v-for="item in documentResources" :key="item.id" class="resource-item">
            <DocumentFileItem 
              :title="item.title" 
              :ossid="item.id" 
              :file-size="item.fileSize" 
              :original-name="item.originalName || item.title" 
              :main-pic="item.mainPic"
            />
          </div>
          <div class="empty-box" v-if="documentResources.length === 0">
            <el-empty description="暂无文档资源" />
          </div>
        </div>
      </div>
      <!--	服务评价（已注释）	-->
      <!-- <div class="service-evaluation">
        <p class="title">服务评价（0）</p>
        <p class="filter">
          <span class="active">全部(0)</span>
          <span>好评(0)</span>
          <span>中评(0)</span>
          <span>差评(0)</span>
        </p>
        <div class="evaluation-list">
          <div class="empty-box">
            <el-empty description="暂无评价" />
          </div>
        </div>
      </div> -->
    </div>
    <div v-else class="loading-box">
      <div class="loading-content">
        <l-tail-chase v-if="isClient" size="60" speed="1.75" color="#1dbf73"></l-tail-chase>
      </div>
    </div>
    <!--	为你推荐（已注释）		-->
    <!-- <div class="recommend">
      <div class="recommend-box">
        <p class="title">为你推荐</p>
        <div class="recommend-list">
          <RecommendingItem
            :dataItem="{}"
            @refresh="toDetails"
          />
        </div>
      </div>
    </div> -->
    <BaseFooter />
  </div>
</template>

<style scoped lang="scss">
.resource-item {
  display: inline-block;
  margin-right: 20px;
  margin-bottom: 20px;
  cursor: pointer;
}

.empty-box {
  width: 100%;
  padding: 40px 0;
  display: flex;
  justify-content: center;
}

.loading-box {
  width: 100%;
  height: 100%;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;

  .loading-fallback {
    font-size: 18px;
    color: #666;
    display: flex;
    align-items: center;

    &::after {
      content: '';
      width: 20px;
      height: 20px;
      border: 2px solid #f3f3f3;
      border-top: 2px solid #1dbf73;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-left: 10px;
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  img {
    width: 600px;
    height: 337px;
  }
}

.info {
  padding-top: 112px;
  display: flex;
}

.content {
  width: 1200px;
  margin: 0 auto;
}

.info-left {
  flex: 0 0 734px;
}

.swiper-box {
  width: 734px;
  height: 474px;
  position: relative;

  .prev {
    position: absolute;
    top: 50%;
    left: 0;
    cursor: pointer;
    z-index: 1;
    margin-top: -30px;

    img {
      width: 60px;
      height: 60px;
    }
  }

  .next {
    position: absolute;
    cursor: pointer;
    top: 50%;
    right: 0;
    z-index: 1;
    margin-top: -30px;

    img {
      width: 60px;
      height: 60px;
    }
  }
}

.swiper-img {
  width: 734px;
  height: 474px;
  border-radius: 24px;
}

.goods-name-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 32px;
  margin-bottom: 16px;
}

.goods-name {
  color: #191e28;
  font-size: 28px;
  font-weight: bold;
  max-width: 600px;
  margin: 0;
}

.copy-button {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  color: #666;

  img {
    width: 16px;
    height: 16px;
  }

  &:hover {
    background: #e9ecef;
    border-color: #dee2e6;
    color: #333;
  }
}

.goods-cate {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 32px;

  span {
    padding: 2px 8px;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    font-size: 12px;
    margin-right: 8px;
    margin-bottom: 5px;
  }

  .class {
    color: #008571;
    background: rgba(0, 133, 113, 0.08);
    border: 1px solid rgba(0, 133, 113, 0.08);
  }
}

.about-info {
  display: flex;
  flex-direction: column;

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    span {
      color: #191e28;
      font-size: 20px;
      font-weight: bold;
    }

    a {
      display: flex;
      align-items: center;
      color: #191e28;
      text-decoration: none;

      img {
        width: 7px;
        height: 14px;
        margin-left: 6px;
        position: relative;
        top: 1px;
      }
    }
  }
}

.user-main-info {
  display: flex;
  align-items: center;
  background: rgba(25, 30, 40, 0.02);
  border-radius: 12px 12px 12px 12px;
  padding: 24px;
  box-sizing: border-box;

  .head {
    width: 60px;
    flex: 0 0 60px;
    height: 60px;
    border-radius: 100%;
    margin-right: 12px;
  }

  .name-info {
    flex: 1;
    display: flex;
    flex-direction: column;

    .name-line {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .name {
        color: #191e28;
        font-weight: bold;
        margin-right: 12px;
      }

      img {
        width: 16px;
        height: 16px;
        margin-right: 4px;
        cursor: pointer;

        &:hover {
          transform: scale(1.1);
        }
      }

      .x-status {
        color: #191e28;
        cursor: pointer;
      }
    }

    .bzj {
      display: flex;
      align-items: center;

      img {
        width: 16px;
        height: 16px;
      }

      span {
        color: rgba(255, 140, 29, 1);
      }
    }
  }

  .line {
    width: 1px;
    height: 40px;
    background: rgba(25, 30, 40, 0.08);
    margin: 0 24px;
  }

  .x-leve {
    display: flex;
    flex-direction: column;

    .x-title {
      color: rgba(25, 30, 40, 0.48);
      font-size: 12px;
      margin-bottom: 2px;
    }

    .x-status {
      color: #191e28;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 2px;
    }

    .status-num {
      color: rgba(25, 30, 40, 0.48);
      font-size: 12px;
    }
  }
}

.info-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-left: 36px;
}

.user-info {
  display: flex;
  box-sizing: border-box;

  .head {
    position: relative;
    width: 56px;
    height: 56px;

    img {
      width: 100%;
      height: 100%;
      border-radius: 100%;
    }

    span {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 12px;
      height: 12px;
      border-radius: 100%;
      border: 2px solid #ffffff;

      &.online {
        background: #1dbf73;
      }

      &.offline {
        background: #999;
      }
    }
  }

  .info-data {
    flex: 1;
    padding-left: 12px;
  }

  .name-line {
    display: flex;
    align-items: center;
    margin-bottom: 6px;

    .name {
      color: #191e28;
      font-size: 20px;
      font-weight: bold;
      margin-right: 12px;
    }

    .follow {
      display: flex;
      align-items: center;
      cursor: pointer;

      img {
        width: 16px;
        height: 16px;
        margin-right: 4px;
        position: relative;
        top: 2px;

        &:hover {
          transform: scale(1.1);
        }
      }

      span {
        color: rgba(25, 30, 40, 0.6);

        &.x-status {
          color: rgba(25, 30, 40, 0.6);

          &.followed {
            color: #ff4757;
          }
        }
      }
    }
  }

  .user-data {
    display: flex;
    align-items: center;

    .online {
      flex: 1;

      span {
        font-size: 12px;
        color: rgba(25, 30, 40, 0.48);
      }

      .status {
        &.online {
          color: #1dbf73;
        }

        &.offline {
          color: #999;
        }
      }
    }

    .star {
      width: 16px;
      height: 16px;
      margin-right: 4px;
    }

    .star-num {
      line-height: 16px;
      color: #191e28;
      font-weight: bold;
    }

    .star-len {
      color: rgba(25, 30, 40, 0.48);
    }
  }
}

.service-details {
  margin-top: 32px;

  .service-tab {
    display: flex;
    border-bottom: 1px solid #ededee;

    span {
      color: #191e28;
      font-size: 20px;
      padding: 12px 24px;

      &.active {
        color: #1dbf73;
        position: relative;

        &:before {
          content: "";
          position: absolute;
          bottom: 0;
          left: 50%;
          margin-left: -17px;
          width: 34px;
          height: 2px;
          background: #1dbf73;
        }
      }
    }
  }
}

.service-content {
  padding: 24px 0;

  img {
    width: 100%;
  }
}

.service-2 {
  display: flex;
  flex-wrap: wrap;
}

.service-4 {
  display: flex;
  flex-wrap: wrap;
}

.service-evaluation {
  .title {
    color: #191e28;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
  }

  .filter {
    margin-bottom: 20px;

    span {
      padding: 4px 8px;
      color: rgba(25, 30, 40, 0.6);
      background: rgba(25, 30, 40, 0.02);
      border-radius: 6px 6px 6px 6px;
      margin-right: 12px;
      cursor: pointer;

      &.active {
        color: #1dbf73;
        background: rgba(29, 191, 115, 0.08);
      }
    }
  }
}

.recommend {
  background: #f9f9f9;
  padding: 32px 0;

  .recommend-box {
    width: 1200px;
    margin: 0 auto;

    .title {
      color: #191e28;
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 24px;
    }
  }

  .recommend-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
</style>
